package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisCacheUtils;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisCacheUtils redisCacheUtils;

    /*
    先从缓存中查询
    缓存中存在，直接返回
    缓存中不存在，先从数据库读取
    数据库不存在，返回失败
    数据库存在，先将结果存入reids，并且返回
     */
    @Override
    public Result queryShopById(Long id) {
        /*String cache = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(cache)){
            Shop shop = JSONUtil.toBean(cache, Shop.class);
            return Result.ok(shop);
        }
        Shop shop_ = getById(id);
        if (shop_==null) {
            return Result.fail("商铺不存在");
        }
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop_));
        //设置过期时间
        stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY+id,RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop_);*/


        //将解决各类缓存问题的方法封装到一个工具类中，通过工具类进行调用。
        /*Shop res = redisCacheUtils.queryWithLogicExpire(RedisConstants.CACHE_SHOP_KEY, Shop.class, id, 10L,
                TimeUnit.SECONDS, i -> getById(id));*/

        Shop shop = redisCacheUtils
                .queryWithPassThrough(CACHE_SHOP_KEY, Shop.class,id, CACHE_SHOP_TTL, TimeUnit.MINUTES,i->getById(id));
        if (shop==null)
            return Result.fail("店铺不存在！");
        return Result.ok(shop);
    }



    //事务注解，保证更新数据库和删除redis缓存是原子性的
    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id==null)
            return Result.fail("商铺id不能为空");
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+id);
        return Result.ok();
    }


}
